package stmo.队列;


import java.util.Iterator;

/**
 *  队列
 */

public class Queue<T> implements Iterable<T>{

    //头结点
    private Node head;

    //尾结点
    private Node last;

    //队列中元素个数
    private int N;

    //成员内部类
    private class Node {

        private T item;

        private Node next;

        public Node(T item,Node next) {
            this.item = item;
            this.next = next;
        }
    }

    //构造方法
    public Queue() {
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }

    //判断队列是否为空
    public boolean isEmpty() {
        return N == 0;
    }

    //返回队列中元素的个数
    public int size() {
        return N;
    }

    //向队列中插入元素t
    public void enqueue(T t) {

        if (last == null) {
            //当前尾结点为null
            Node addNode = new Node(t,null);
            head.next = addNode;
            this.last = addNode;
        }else {
            //当前尾结点不为null
            Node addNode = new Node(t,null);
            this.last.next = addNode;
            this.last = addNode;
        }
        N++;
    }

    //向队列中拿出一个元素
    public T dequeue() {

        if (isEmpty()) {
            return null;
        }

        Node oldNode = head.next;
        head.next = oldNode.next;
        N--;
        if (isEmpty()) {
            last = null;
        }
        return oldNode.item;
    }

    /**
     *   遍历
     */

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    public class QIterator implements Iterator{

        private Node n;

        public QIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}

